import _ from "lodash";
import fs from "fs";
import path from "path";
// 批量写入文件

interface Task {
  fileName: string; // 保证要唯一
  data: Buffer;
}

export function writeFiles(tasks: Task[], basePath: string): Promise<boolean> {
  return new Promise((res, rej) => {
    let base = basePath || process.cwd();
    let ap: string; // 绝对路径
    let error: NodeJS.ErrnoException | null = null;
    // 遍历任务序列
    _(tasks).each((task) => {
      ap = path.resolve(basePath, task.fileName);
      fs.writeFile(ap, task.data, (err) => {
        error = err;
      });

      if (_.isNull(error)) {
        rej(error);
      } else {
        res(true); // 全部写入完成
      }
    });
  });
}
